package gameEngine;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseEvent;

import javax.swing.event.MouseInputAdapter;

import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.swing.JSVGCanvas;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Element;
import org.w3c.dom.svg.SVGDocument;

public class PieceView extends ViewSon {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4357073549987546923L;
	Piece piece;
	protected Square[] miniBoard;
	
	DOMImplementation impl;
	String svgNS;
	SVGDocument doc;
	SVGGraphics2D miniBoardContainer;
	JSVGCanvas canvas;
	Element root;
	int squareSize;
	int pieceSize;
	Square pointer;
	Engine controller;
	
	public PieceView(Piece _piece, Engine _controller) {
		super();
		this.controller = _controller;
		piece = _piece;
		pieceSize = piece.getSize();
		miniBoard = new Square[pieceSize * pieceSize];
		
		impl = SVGDOMImplementation.getDOMImplementation();
		svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
		doc = (SVGDocument) impl.createDocument(svgNS, "svg", null);
		miniBoardContainer = new SVGGraphics2D(doc);
		
		squareSize = Square.getDefaultSize()/2;
		Dimension d = new Dimension(pieceSize*(squareSize+(squareSize/20)), pieceSize*(squareSize+(squareSize/20)));
		
		miniBoardContainer.setSVGCanvasSize(d);
		pointer = new Square();
		
		this.addMouseListener(new MouseInputAdapter() {
			public void mouseClicked(MouseEvent e) {
				System.out.println("Mouse was clicked on a piece");
				controller.setCurrentPiece(piece);
			}
		});
		
		for(int i = 0; i < pieceSize * pieceSize; i++) {
			int x, y;
			x = i % pieceSize;
			y = i / pieceSize;
			pointer.setLocation(x+(x*squareSize), y+(y*squareSize));
			if(piece.render()[x][y] == 1) {
				miniBoardContainer.setColor(piece.get親().getColor());
				//miniBoardContainer.setColor(Color.blue);
			}
			else {
				miniBoardContainer.setColor(Color.pink);
			}
			miniBoardContainer.fill(pointer);
			miniBoardContainer.setColor(Color.black);
			miniBoardContainer.draw(pointer);
		}
		
		root = doc.getDocumentElement();
		miniBoardContainer.getRoot(root);
		
		canvas = new JSVGCanvas();
		canvas.setDoubleBuffered(true);
		canvas.setDoubleBufferedRendering(true);
		canvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
		canvas.setSize(d);
		canvas.setSVGDocument(doc);
		canvas.addMouseListener(new MouseInputAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				callMouseClicked(e);
			}
		});
		
		this.add(canvas);
	}
	
	public void callMouseClicked(MouseEvent e) {
		this.getMouseListeners()[0].mouseClicked(e);
	}


}
